#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"

using namespace ns_log;

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        LOG(WARNING) << "usage: " << argv[0] << "serverip serverport" << std::endl;
        return -1;
    }
    std::string serverip = argv[1];
    int serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        LOG(ERROR) << "创建套接字失败" << std::endl;
        return -1;
    }

    std::string message;
    while(true)
    {
        std::cout << "请输入消息：";
        getline(std::cin, message);

        int n = sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr *)&server, sizeof(server));
        if(n > 0)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            int ret = recvfrom(sockfd, buffer, sizeof(buffer), 0, (sockaddr *)&peer, &len);
            if(ret > 0)
            {
                buffer[ret] = 0;
                LOG(INFO) << "[" << peer.sin_addr.s_addr << ":" << peer.sin_port << "]: " << buffer << std::endl;
            }
            else
            {
                LOG(WARNING) << "接受消息失败" << std::endl;
            }
        }
    }
    return 0;
}